var express = require('express');
var fs = require('fs');
var fse = require('fs-extra');
var router = express.Router();
var creator = require('../codegen/creator');
var packager = require('../codegen/utils/packager');
var jscomment = require('strip-json-comments');

router.use('/', function (req, res, next) {
    var p = req.body.project;
    var k = req.body.package;
    var j = req.body.jsonstr;
    var cls = req.body.root_class;
    var lang = req.body.lang;
    var type = req.body.source;
    var rules = req.body.rulestr;
    if (!isNotNull(lang)) {
        lang = 'java';
    }
    var mapping = req.body.mapping === 'on';
    if (!isNotNull(mapping)) {
        mapping = true;
    }
    if (isNotNull(p) &&
        isNotNull(k) &&
        isNotNull(type)) {
        if (!((type === 'rule' && isNotNull(rules)) || (type === 'text' && isNotNull(j)))) {
            res.render('index');
            return;
        }
        if (type === 'rule') {
            var reqs = JSON.parse(rules);
            var flag = reqs.length;
            for (var i = 0; i < reqs.length; i++) {
                var acls = reqs[i]['root_cls'];
                var reqModel = reqs[i]['request_model'];
                creator.withRequestModel(reqModel, acls, lang, p, k, mapping, function () {
                    flag--;
                    if (flag === 0) {
                        packager(p, lang, function (r) {
                                if (r !== undefined) {
                                    var options = {
                                        headers: {
                                            'Content-Disposition': 'inline; filename=' + p + '.zip'
                                        }
                                    };
                                    res.sendFile(r, options, function () {
                                        fse.removeSync(r);
                                    });
                                }
                                else {
                                    var err = new Error('失败！');
                                    err.status = 500;
                                    next(err);
                                }
                            }
                        );
                    }
                });
            }
        } else {
            if (!isNotNull(cls)) {
                res.render('index');
                return;
            }
            var jsObj;
            j = jscomment(j);
            try {
                jsObj = JSON.parse(j);
            } catch (e) {
                var err = new Error('JSON格式不正确！');
                err.status = 500;
                next(err);
                return;
            }
            creator.withJsonObject(jsObj, cls, lang, p, k, mapping, function () {
                packager(p, lang, function (r) {
                        if (r !== undefined) {
                            var options = {
                                headers: {
                                    'Content-Disposition': 'inline; filename=' + p + '.zip'
                                }
                            };
                            res.sendFile(r, options, function () {
                                fse.removeSync(r);
                            });
                        }
                        else {
                            var err = new Error('失败！');
                            err.status = 500;
                            next(err);
                        }
                    }
                );
            });
        }
    } else {
        res.render('index');
    }
});

function isNotNull(str) {
    return str != null ? str !== undefined ? str !== '' : false : false;
}

module.exports = router;
